package com.showde.shoppingmall.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.showde.shoppingmall.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;

public class PersistentComponent {

	public static Drawable persistent2Drawable(View view)
			throws FileNotFoundException {
		view.setDrawingCacheEnabled(true);
		view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		if (bitmap != null) {
			bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(
					new File("sdcard/sp.png")));
			BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
			return bitmapDrawable;
		}
		return null;
	}

	public static Bitmap persistent2Bitmap(View view)
			throws FileNotFoundException {
		view.setDrawingCacheEnabled(true);
		view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		if (bitmap != null) {
			return bitmap;
		}
		return null;
	}

	public static Drawable generateTargetDrawable(Context context, int rsid,
			int targetViewId) {
		// 原代码会引起异常
		// http://blog.csdn.net/xiaoxiaobian3310903/article/details/6798436
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
				rsid).copy(Bitmap.Config.ARGB_8888, true);
		Bitmap targetBitmap = BitmapFactory.decodeResource(
				context.getResources(), targetViewId);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint();
		canvas.drawBitmap(targetBitmap, 95, 0, paint);
		paint.setColor(Color.WHITE);
		paint.setTextSize(24);
		canvas.drawText("3", 110, 30, paint);
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();
		BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
		return bitmapDrawable;
	}
}
